package patientimport;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SynchOldFollow {

    public static final String GET_URL = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
    public static final String POST_URL_CALL = "http://192.168.1.38:8080/v21/power/babyFollowScheme/usedShcmemByFirstRecord";
    //public static final String POST_URL_CALL = "http://doctor.bb-care.com/v26/power/babyFollowScheme/usedShcmemByFirstRecord";
    public static final String POST_URL = "http://192.168.1.38:8080/v21/web/doLogin";
   // public static final String POST_URL = "http://doctor.bb-care.com/v26/web/doLogin";
    public static final String POST_URL_TEMP = "http://192.168.1.38:8080/v21/power/babyFollowSchemeTask/getTemp";
    // public static final String username = "18017591123"; //生产周医生账号
    public static final String username = "13865958283"; // 测试账号
    public static final String password = "958283";

    /**
     * 接口调用 GET
     */
    public static void httpURLConectionGET() {
        try {
            URL url = new URL(GET_URL); // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
    }

    /**
     * 接口调用 POST
     */
    public static String httpURLConnectionPOST() {
        String cookie = null;
        try {
            URL url = new URL(POST_URL);
            System.out.println("url==" + POST_URL);

            // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接
            // (标识一个url所引用的远程对象连接)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中

            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);

            // 设置请求方式为post
            connection.setRequestMethod("POST");

            // post请求缓存设为false
            connection.setUseCaches(true);

            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);
            // String setCookie = connection.getHeaderField("Set-Cookie");
            // System.out.println("cook11=="+setCookie);
            // connection.setRequestProperty("Cookie", cookie);

            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据
            // application/x-javascript->json对象
            // application/x-www-form-urlencoded->表单数据
            // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            // 建立连接
            // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

            // 格式 parm = aaa=111&bbb=222&ccc=333
            String parm1 = "username=" + URLEncoder.encode(username, "utf-8") + "&password="
                    + URLEncoder.encode(password, "utf-8");
            System.out.println("param1==[" + parm1 + "]");

            // 将参数输出到连接
            dataout.writeBytes(parm1);

            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

            String setCookie2 = connection.getHeaderField("Set-Cookie");
            System.out.println("cook22==[" + setCookie2 + "]");
            if (null == setCookie2) {
                System.out.println("---login failed 111---");
                return null;
            }
            cookie = setCookie2.substring(0, setCookie2.indexOf(";"));
            System.out.println("cookie==[" + cookie + "]");
            Map<String, List<String>> t123 = connection.getHeaderFields();
            System.out.println(t123.toString());

            // System.out.println(connection.getResponseCode());

            // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据
            StringBuilder ttt = new StringBuilder();

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                // sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
                ttt.append(line);
            }
            bf.close(); // 重要且易忽略步骤 (关闭流,切记!)

            // httpURLConnectionPOSTcall(t123);
            System.out.println("---" + sb.toString());
            // connection.disconnect(); // 销毁连接

            connection.disconnect(); // 销毁连接
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cookie;
    }

    public static void httpURLConnectionPOSTcall(String cookie, Map<String, String> parmap) throws Exception {
        try {
            URL url = new URL(POST_URL_CALL);
            System.out.println("url==" + POST_URL_CALL);

            // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接
            // (标识一个url所引用的远程对象连接)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中

            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);

            // 设置请求方式为post
            connection.setRequestMethod("POST");

            // post请求缓存设为false
            connection.setUseCaches(true);

            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);

            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据
            // application/x-javascript->json对象
            // application/x-www-form-urlencoded->表单数据
            // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.setRequestProperty("Cookie", cookie);

            // 建立连接
            // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

            // 格式 parm = aaa=111&bbb=222&ccc=333 13956971999
            /*
             * String parm_for_test = "userId=" +
             * URLEncoder.encode(parmap.get("userId"), "utf-8") +
             * "&followQueueId=" +
             * URLEncoder.encode("297ebe0e5bf1bcd9015bf2432a19086a", "utf-8") +
             * "&answer=" + URLEncoder.encode("[{\"answer\":" + "\"" +
             * parmap.get("phoneNo") +
             * "\",\"id\":\"297ebe0e56b078650150b5263a2f08c7\",\"basicColumn\":\"phoneNo\",\"type\":\"12\",\"note\":\"手机号码\"},"
             * + "{\"answer\":\"" + parmap.get("babyName") +
             * "\",\"id\":\"297ebe0e56b078680156b5263aac08c8\",\"basicColumn\":\"babyName\",\"type\":\"3\",\"note\":\"患者姓名\"},"
             * + "{\"answer\":[\"" + parmap.get("gender") +
             * "\"],\"id\":\"297ebe0e56b075650156b5263b1908c9\",\"basicColumn\":\"gender\",\"type\":\"1\",\"note\":\"性别\"},"
             * + "{\"answer\":\"" + parmap.get("birthday") +
             * "\",\"id\":\"297ebe0e56b078250156b5263b2908cc\",\"basicColumn\":\"birthday\",\"type\":\"6\",\"note\":\"出生日期\"},"
             * // + //
             * "{\"answer\":\"2017-3-1\",\"id\":\"297ebe0e56b078250156b5263b2908cf\",\"basicColumn\":\"dueDate\",\"type\":\"6\",\"note\":\"预产期\"},"
             * + "{\"answer\":\"" + parmap.get("pregnancyWeek") +
             * "\",\"id\":\"297ebb0e56b078650156b5263c1308ce\",\"basicColumn\":\"pregnancyWeek\",\"type\":\"17\",\"note\":\"出生胎龄\"}]",
             * "utf-8");
             */
            String parm2 = "userId=" + URLEncoder.encode("", "utf-8") + "&followQueueId="
                    + URLEncoder.encode("f9abe0c15b9051e5015bf2f3614104cd", "utf-8") + "&answer="
                    + URLEncoder.encode("[" + "  {" + "    \"answer\": \"" + parmap.get("phoneNo") + "\","
                            + "    \"id\": \"aydysyu0000001\"," + "    \"basicColumn\": \"phoneNo\","
                            + "    \"type\": \"9\"," + "    \"note\": \"手机号码\"" + "  }," + "  {" + "    \"answer\": \""
                            + parmap.get("babyName") + "\"," + "    \"id\": \"aydysyu0000002\","
                            + "    \"basicColumn\": \"babyName\"," + "    \"type\": \"3\"," + "    \"note\": \"患者姓名\""
                            + "  }," + "  {" + "    \"answer\": [" + "      \"N\"" + "    ],"
                            + "    \"id\": \"aydysyu0000003\"," + "    \"basicColumn\": \"gender\","
                            + "    \"type\": \"1\"," + "    \"note\": \"性别\"" + "  }," + "  {" + "    \"answer\": \""
                            + parmap.get("birthday") + "\"," + "    \"id\": \"aydysyu0000004\","
                            + "    \"basicColumn\": \"birthday\"," + "    \"type\": \"6\"," + "    \"note\": \"出生日期\""
                            + "  }," + "  {" + "    \"answer\": \"" + parmap.get("birthday") + "\","
                            + "    \"id\": \"aydysyu0000005\"," + "    \"basicColumn\": \"dueDate\","
                            + "    \"type\": \"6\"," + "    \"note\": \"预产期\"" + "  }," + "  {"
                            + "    \"answer\": \"280\"," + "    \"id\": \"aydysyu0000006\","
                            + "    \"basicColumn\": \"pregnancyWeek\"," + "    \"type\": \"17\","
                            + "    \"note\": \"出生胎龄\"" + "  }," + "  {" + "    \"answer\": \"" + parmap.get("ma_phone")
                            + "\"," + "    \"id\": \"aydysyu0000007\"," + "    \"basicColumn\": \"\","
                            + "    \"type\": \"9\"," + "    \"note\": \"妈妈手机号码\"" + "  }," + "  {"
                            + "    \"answer\": \"" + parmap.get("fa_phone") + "\"," + "    \"id\": \"aydysyu0000008\","
                            + "    \"basicColumn\": \"\"," + "    \"type\": \"9\"," + "    \"note\": \"爸爸手机号码\""
                            + "  }," + "  {" + "    \"answer\": \"" + parmap.get("grapa_phone") + "\","
                            + "    \"id\": \"aydysyu0000009\"," + "    \"basicColumn\": \"\"," + "    \"type\": \"9\","
                            + "    \"note\": \"爷爷奶奶手机号码\"" + "  }," + "  {" + "    \"answer\": \""
                            + parmap.get("law_grapa_phone") + "\"," + "    \"id\": \"aydysyu00000010\","
                            + "    \"basicColumn\": \"\"," + "    \"type\": \"9\"," + "    \"note\": \"外公外婆手机号码\""
                            + "  }," + "  {" + "    \"answer\": \"" + parmap.get("id_no") + "\","
                            + "    \"id\": \"aydysyu00000011\"," + "    \"basicColumn\": \"\"," + "    \"type\": \"3\","
                            + "    \"note\": \"编号\"" + "  }" + "]", "utf-8");

            //System.out.println("parm_for_test==[" + parm2 + "]");

            // 将参数输出到连接
            dataout.writeBytes(parm2);

            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

            // System.out.println(connection.getResponseCode());

            // Map<String, List<String>> ggg = connection.getHeaderFields();
            // System.out.println(ggg.toString());

            // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                // sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
            }
            System.out.println("---" + sb.toString());
            bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
        } catch (Exception e) {
            e.printStackTrace();
            throw (e);
        }
    }

    public static void getDataFromDB(String cookie) {
        int irow = 0;
        int succNum = 0;
        int errNum = 0;
        int icontinue = 0;
        // 声明Connection对象
        Connection con;
        // 驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名mydata
        String url = "jdbc:mysql://rdsap8226j2iuruyoaamgpublic.mysql.rds.aliyuncs.com/test_test";
        // MySQL配置时的用户名
        String user = "zh_xiong";
        // MySQL配置时的密码
        String password = "xzh123456";
        // 遍历查询结果集
        try {
            // 加载驱动程序
            Class.forName(driver);
            // 1.getConnection()方法，连接MySQL数据库！！
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed())
                System.out.println("Succeeded connecting to the Database!");
            // 2.创建statement类对象，用来执行SQL语句！！
            Statement statement = con.createStatement();
            // 要执行的SQL语句
            String sql = "select  id_no, birthday, user_name, ma_phone,"
                    + " fa_phone, home_phone, grapa_phone, law_grapa_phone from temp_followuser_170509"
                    + " where user_name not in('王轩辕','尹嘉宁')";
            System.out.println("sql==" + sql);
            // 3.ResultSet类，用来存放获取的结果集！！
            ResultSet rs = statement.executeQuery(sql);
            System.out.println("-----------------");
            System.out.println("执行结果如下所示:");
            System.out.println("-----------------");

            String birthday = null;

            String id_no = null;
            String user_name = null;
            String ma_phone = null;
            String fa_phone = null;
            String home_phone = null;
            String grapa_phone = null;
            String law_grapa_phone = null;


            Map<String, String> params = null;
            while (rs.next()) {
                params = new HashMap<String, String>();
                irow++;

                id_no = rs.getString("id_no");
                birthday = rs.getString("birthday");
                user_name = rs.getString("user_name");
                ma_phone = rs.getString("ma_phone");
                fa_phone = rs.getString("fa_phone");
                home_phone = rs.getString("home_phone");
                grapa_phone = rs.getString("grapa_phone");
                law_grapa_phone = rs.getString("law_grapa_phone");

                if (StringUtils.isEmpty(birthday)) {
                    icontinue++;
                    continue;
                }
                if (StringUtils.isEmpty(user_name)) {
                    icontinue++;
                    continue;
                }

                if (!StringUtils.isEmpty(ma_phone)) {
                    params.put("phoneNo", ma_phone);
                } else if (!StringUtils.isEmpty(fa_phone)) {
                    params.put("phoneNo", fa_phone);
                } else if (!StringUtils.isEmpty(home_phone)) {
                    params.put("phoneNo", home_phone);
                } else if (!StringUtils.isEmpty(grapa_phone)) {
                    params.put("phoneNo", grapa_phone);
                } else if (!StringUtils.isEmpty(law_grapa_phone)) {
                    params.put("phoneNo", law_grapa_phone);
                } else {
                    icontinue++;
                    continue;
                }

                params.put("id_no", id_no);
                params.put("babyName", user_name);
                params.put("gender", "N");
                params.put("birthday", birthday);
                params.put("pregnancyWeek", "280");
                params.put("userId", "");
                params.put("ma_phone", ma_phone);
                params.put("fa_phone", fa_phone);
                params.put("grapa_phone", grapa_phone);
                params.put("law_grapa_phone", law_grapa_phone);
                // 输出结果
                System.out.println(irow + ":  " + params.get("phoneNo") + "\t" + user_name + "\t" + "N" + "\t"
                        + birthday + "\t" + "280" + "\t" + "");
                try {
                    httpURLConnectionPOSTcall(cookie, params);
                    succNum++;
                } catch (Exception ex) {
                    errNum++;
                    ex.printStackTrace();
                }

            }
            rs.close();
            con.close();
        } catch (ClassNotFoundException e) {
            // 数据库驱动类异常处理
            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();
        } catch (SQLException e) {
            // 数据库连接失败异常处理
            e.printStackTrace();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            System.out.println("总记录: "+irow);
            System.out.println("skip: "+icontinue);
            System.out.println("success: "+succNum);
            System.out.println("error: "+errNum);
        }
    }

    public static void httpURLConnectionTest(String cookie) {
        try {
            URL url = new URL(POST_URL_TEMP);
            System.out.println("url==" + POST_URL_TEMP);

            // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接
            // (标识一个url所引用的远程对象连接)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中

            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);

            // 设置请求方式为post
            connection.setRequestMethod("POST");

            // post请求缓存设为false
            connection.setUseCaches(true);

            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);

            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据
            // application/x-javascript->json对象
            // application/x-www-form-urlencoded->表单数据
            // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.setRequestProperty("Cookie", cookie);

            // 建立连接
            // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

            // 格式 parm = aaa=111&bbb=222&ccc=333 13956971999
            String parm_for_test = "babyid=" + URLEncoder.encode("297ebe0e59681a6701596833d9f50b22", "utf-8");

            System.out.println("parm_for_test==[" + parm_for_test + "]");

            // 将参数输出到连接
            dataout.writeBytes(parm_for_test);

            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

            // System.out.println(connection.getResponseCode());

            // Map<String, List<String>> ggg = connection.getHeaderFields();
            // System.out.println(ggg.toString());

            // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                // sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
            }
            System.out.println("---" + sb.toString());
            bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // httpURLConectionGET();
        String cookie = httpURLConnectionPOST();
        if (null == cookie) {
            System.out.println("---login failed---");
            return;
        }
        getDataFromDB(cookie);
        // httpURLConnectionTest(cookie);
    }
}
